package love.yuanmengrobot.attendancesystem.servlet;

import com.google.gson.Gson;
import love.yuanmengrobot.attendancesystem.dao.MemberDao;
import love.yuanmengrobot.attendancesystem.entity.Member;

import java.io.IOException;
import java.io.PrintWriter;

public class LoginServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        System.out.println("post");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        String paw = request.getParameter("paw");
        String perm=request.getParameter("permission");

        login(id,paw,perm,request,response);


    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        System.out.println("get");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String id = request.getParameter("id");
        String paw = request.getParameter("paw");
        String perm=request.getParameter("permission");
        login(id,paw,perm,request,response);

    }
    public void login(String id,String paw,String perm,javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response){

        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Gson gson=new Gson();

        MemberDao memberDao = new MemberDao();
        Member member = memberDao.queryById(id, paw,perm);

        if (member != null) {
            member.setMeg("登录成功");
            pw.print(gson.toJson(member));
            request.getSession().setAttribute("member",member);
        } else {
            pw.print("{\"meg\":\"登录失败\"}");
        }
        pw.flush();
        pw.close();
    }

}
